package com.joymart.common.data.jdbc;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsonorg.JsonOrgModule;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import org.json.JSONArray;
import org.json.JSONObject;
import org.postgresql.util.PGobject;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;
import org.springframework.data.convert.ReadingConverter;
import org.springframework.data.convert.WritingConverter;
import org.springframework.data.jdbc.repository.config.AbstractJdbcConfiguration;

import java.sql.SQLException;
import java.util.Arrays;
import java.util.List;

@Configuration
public class WithwingsJdbcConfiguration extends AbstractJdbcConfiguration {

    @Override
    protected List<?> userConverters() {
        return Arrays.asList(new JSONWritingConverter(),
                new JSONReadingConverter());
    }

    @WritingConverter
    public static class JSONWritingConverter implements Converter<JSONObject, PGobject> {

        @Override
        public PGobject convert(JSONObject source) {
            PGobject jsonObject = new PGobject();
            jsonObject.setType("json");
            try {
                jsonObject.setValue(source.toString());
            } catch (SQLException throwables) {
                throw new RuntimeException(throwables);
            }
            return jsonObject;
        }


    }

    @ReadingConverter
    public static class JSONReadingConverter implements Converter<PGobject, JSONObject> {

        @Override
        public JSONObject convert(PGobject pg) {
            String source = pg.getValue();
            return new JSONObject(source);
        }
    }


 }
